﻿using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using Swagger.WebApi;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;

namespace HpaApi.WebApi
{
    /// <summary>
    /// 
    /// </summary>
    public class InterfaceContractResolver : DefaultContractResolver
    {
        //private readonly ConcurrentDictionary<Type, Type> _typeToSerializeMap;
        //private List<Type> _interfaceTypeList;
        /// <summary>
        /// 
        /// </summary>
        public InterfaceContractResolver()
        {
            //_interfaceTypeList = new List<Type>();
            //_typeToSerializeMap = new ConcurrentDictionary<Type, Type>();
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        //public override JsonContract ResolveContract(Type type)
        //{
        //    return base.ResolveContract(type);
        //}
        /// <summary>
        /// 
        /// </summary>
        /// <param name="type"></param>
        /// <param name="memberSerialization"></param>
        /// <returns></returns>
        protected override IList<JsonProperty> CreateProperties(
            Type type,
            MemberSerialization memberSerialization)
        {

            var attribute=type.GetCustomAttributes<JsonSerializeAttribute>();
            Type typeToSerialize = null;
            if (attribute.Count() > 0)
            {
                typeToSerialize = attribute.First().SerializeType;
            }
            else
                typeToSerialize = type;


            //if (type.IsInterface)
            //{
            //    _interfaceTypeList.Add(type);
            //}

            //var typeToSerialize = _typeToSerializeMap.GetOrAdd(
            //                           type,
            //                           t => _interfaceTypeList.FirstOrDefault(it => it.IsAssignableFrom(t)) ?? t);

            return base.CreateProperties(typeToSerialize, memberSerialization);
        }
    }
}